package com.hj.auth.common.handler;

import com.alibaba.fastjson.JSON;
import com.hj.auth.common.pojo.LoginUser;
import com.hj.auth.common.util.JwtTokenUtil;
import com.hj.common.pojo.model.AjaxResult;
import com.hj.common.util.ServletUtils;
import com.hj.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 退出成功后处理器
 */
@Component
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;


    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        LoginUser loginUser = jwtTokenUtil.getLoginUser(request);
        //如果redis有用户信息 需要删除redis缓存后退出
        if (StringUtils.isNotNull(loginUser)){
            jwtTokenUtil.delLoginUser(loginUser.getToken());
            ServletUtils.sendString(response, JSON.toJSONString(AjaxResult.success("退出成功")));
            return;
        }
        ServletUtils.sendString(response, JSON.toJSONString(AjaxResult.success("退出成功")));
    }
}
